//
//  UIViewController.swift
//  UIViewController
//
//  Created by mini on 2025/4/28.
//

import Foundation
import UIKit

private var key_blockBack_UIViewController: UInt8 = 0
private var key_blockWillBack_UIViewController: UInt8 = 0
private var key_requestState_UIViewController: UInt8 = 0

extension UIViewController {

    var requestState: Int {
        get {
            if let num = objc_getAssociatedObject(self, &key_requestState_UIViewController) as? NSNumber {
                return num.intValue
            }
            return 0
        }
        set(newValue) {
            objc_setAssociatedObject(self, &key_requestState_UIViewController, NSNumber(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var blockBack: ((UIViewController) -> Void)? {
        get {
            return objc_getAssociatedObject(self, &key_blockBack_UIViewController) as? ((UIViewController) -> Void)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &key_blockBack_UIViewController, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var blockWillBack: ((UIViewController) -> Void)? {
        get {
            return objc_getAssociatedObject(self, &key_blockWillBack_UIViewController) as? ((UIViewController) -> Void)
        }
        set(newValue) {
            objc_setAssociatedObject(self, &key_blockWillBack_UIViewController, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

//    // 设置blockWillBack
//    self.blockWillBack = { viewController in
//        // 在这里执行您想要的操作，比如返回上一个视图控制器
//        GB_Nav?.popViewController(animated: true)
//    }
//    // 在需要的地方调用 self.blockWillBack?(self)
//    self.blockWillBack?(self)

    // MARK: - 删除子VC
    func removeAllChildVC() {
        while children.count > 0 {
            if let childVC = children.last {
                childVC.view.removeFromSuperview()
                childVC.removeFromParent()
            }
        }
    }

    // MARK: - 获取最顶层控制器
    func topMostViewController() -> UIViewController {
        if let presented = presentedViewController {
            return presented.topMostViewController()
        }
        return self
    }
}
